'''
根据立讯的C算法, 转成python算法实现
'''

# ----------------------------
def crc8(data):
    t_crc = 0xFF
    for byte in data:
        t_crc ^= byte
        for _ in range(8):
            if t_crc & 0x80:
                t_crc <<= 1
                t_crc ^= 0x1D
            else:
                t_crc <<= 1
    return ~t_crc & 0xFF


def seedToKey_L5(seed):
    seedlength = 6
    buf_byte = [0] * 6
    crc_byte = [0] * 7

    seed += [0x4C, 0x55]

    buf_byte[0] = seed[0]
    buf_byte[1] = seed[1]
    buf_byte[2] = seed[2]
    buf_byte[3] = seed[3]
    buf_byte[4] = seed[4]
    buf_byte[5] = seed[5]

    crc_byte[0] = crc8(buf_byte[:seedlength])

    buf_byte[0] = crc_byte[0]
    crc_byte[1] = crc8(buf_byte[:seedlength])

    buf_byte[0] = seed[0]
    buf_byte[1] = crc_byte[1]
    crc_byte[2] = crc8(buf_byte[:seedlength])

    buf_byte[1] = seed[1]
    buf_byte[2] = crc_byte[2]
    crc_byte[3] = crc8(buf_byte[:seedlength])

    buf_byte[2] = seed[2]
    buf_byte[3] = crc_byte[3]
    crc_byte[4] = crc8(buf_byte[:seedlength])

    buf_byte[3] = seed[3]
    buf_byte[4] = crc_byte[4]
    crc_byte[5] = crc8(buf_byte[:seedlength])

    buf_byte[4] = seed[4]
    buf_byte[5] = crc_byte[5]
    crc_byte[6] = crc8(buf_byte[:seedlength])

    if crc_byte[3] == 0 and crc_byte[4] == 0 and crc_byte[5] == 0 and crc_byte[6] == 0:
        res = [crc_byte[1], crc_byte[2], crc_byte[3], crc_byte[4]]

    else:
        res = [crc_byte[3], crc_byte[4], crc_byte[5], crc_byte[6]]

    # print("res:", res)
    # res = [hex(item)[2:].upper().zfill(2) for item in res]

    return res



# # # 测试一下seedToKey_L5
# # seed = [0x75, 0xA3, 0xD1, 0x67]
# seed = [177, 209, 42, 142]
# key = []
# actual_key_size = 4
# res = seedToKey_L5(seed)
# print(res)

